/**
 * 
 */
package app.tuwien.isi.tweetanalyser;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * @author Philipp Pospisil
 *
 */
public class StatisticDetailsActivity extends Activity{

	Spinner spinnerSort;
	Button mapButton;
	
	private StatisiticDetailsAdapter ExpAdapter;
	private ArrayList<ListGroup> ExpListItems;
	private ExpandableListView ExpandList;
	
	private String[] place;
	private int[] sum;
	private String[] type;
	private String[] country;
	private String[] coordinates;
	
	private String[] user;
	private String[] location;
	private String[] language;
	private int[] followers;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.statistic_details);
		
		spinnerSort = (Spinner) findViewById(R.id.spinnerSortDetails);
		
		mapButton = (Button) findViewById(R.id.buttonMapsStatistic);
        
        Intent intent = getIntent();
		
        if(intent.getStringExtra("statistic") == null){
        	Log.e("statistic","is null at StatisticDetailsActivity");
        }else{
        	String statisticTyp = intent.getStringExtra("statistic");
        	
        	if(statisticTyp.equals("place")){
        		PlaceStatistic(intent);
        	}else{
        		if(statisticTyp.equals("user")){
            		UserStatistic(intent);
            	}
        	}
        }
	}
	
	public void PlaceStatistic (Intent intent){
		
        String sortString[] = {"sort by","Name","Count","Typ","Country"};
        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, sortString);
        spinnerSort.setAdapter(spinnerArrayAdapter); 
		
        spinnerSort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
			
			public void  onItemSelected(AdapterView<?> parent, View view, int position, long id){
				if(position != 0){
					sort(position);
					ExpandList.invalidateViews();
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {		
			}
		});
        
        mapButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Intent intent = new Intent (getApplicationContext(), LocationActivity.class);
            	
            	if(ExpListItems == null){
            		Log.e("ExpListItems","is null at mapButtonListener (Place)");
            	}else{
            		int size = ExpListItems.size();
            		String[] intentplace = new String[size];
            		String[] intentsum = new String[size];
            		String[] intenttype = new String[size];
            		String[] intentcountry = new String[size];
            		String[] intentcoordinates = new String[size];
            		
            		for(int i=0;i<size;i++){
            			intentplace[i] = ExpListItems.get(i).getName();
            			intentsum[i] = ExpListItems.get(i).getItems().get(0).getName();
            			intenttype[i] = ExpListItems.get(i).getItems().get(1).getName();
            			intentcountry[i] = ExpListItems.get(i).getItems().get(2).getName();
            			intentcoordinates[i] = ExpListItems.get(i).getItems().get(3).getName().substring(13);
            		}
            		intent.putExtra("statistic", "place");
	            	intent.putExtra("place", intentplace);
	            	intent.putExtra("sum", intentsum);
	            	intent.putExtra("type", intenttype);
	            	intent.putExtra("country", intentcountry);
	            	intent.putExtra("coordinates", intentcoordinates);
	            	startActivityForResult(intent, 1);
            	}
            }
        });
        
		if(intent.getStringArrayExtra("place") == null){
			Log.e("place","is null at StatisticDetailsActivity");
		}else{
			place = intent.getStringArrayExtra("place");

			if(intent.getIntArrayExtra("sum") == null){
				Log.e("sum","is null at StatisticDetailsActivity");
			}else{
				sum = intent.getIntArrayExtra("sum");
				type = intent.getStringArrayExtra("type");
				country = intent.getStringArrayExtra("country");
				coordinates = intent.getStringArrayExtra("coordinates");
				
				ExpandList = (ExpandableListView) findViewById(R.id.expandableList);
				
				ExpListItems = SetPlaceGroups();
				
				ExpAdapter = new StatisiticDetailsAdapter(StatisticDetailsActivity.this, ExpListItems);
		        ExpandList.setAdapter(ExpAdapter);
			}
		}
	}
	
	public void UserStatistic (Intent intent){
		
        String sortString[] = {"sort by","Name","Count","Location","Language","Followers"};
        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, sortString);
        spinnerSort.setAdapter(spinnerArrayAdapter); 
		
        spinnerSort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
			
			public void  onItemSelected(AdapterView<?> parent, View view, int position, long id){
				if(position != 0){
					sort(position);
					ExpandList.invalidateViews();
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {		
			}
		});
        
        mapButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Intent intent = new Intent (getApplicationContext(), LocationActivity.class);
            	
            	if(ExpListItems == null){
            		Log.e("ExpListItems","is null at mapButtonListener (Place)");
            	}else{
            		int size = ExpListItems.size();
            		String[] intentuser = new String[size];
            		String[] intentsum = new String[size];
            		String[] intentlocation = new String[size];
            		String[] intentlanguage = new String[size];
            		String[] intentfollowers = new String[size];
            		
            		for(int i=0;i<size;i++){
            			intentuser[i] = ExpListItems.get(i).getName();
            			intentsum[i] = ExpListItems.get(i).getItems().get(0).getName();
            			intentlocation[i] = ExpListItems.get(i).getItems().get(1).getName().substring(10);
            			intentlanguage[i] = ExpListItems.get(i).getItems().get(2).getName();
            			intentfollowers[i] = ExpListItems.get(i).getItems().get(3).getName();
            		}
            		intent.putExtra("statistic", "user");
	            	intent.putExtra("user", intentuser);
	            	intent.putExtra("sum", intentsum);
	            	intent.putExtra("location", intentlocation);
	            	intent.putExtra("language", intentlanguage);
	            	intent.putExtra("followers", intentfollowers);
	            	startActivityForResult(intent, 1);
            	}
            }
        });
        
		if(intent.getStringArrayExtra("user") == null){
			Log.e("user","is null at StatisticDetailsActivity");
		}else{
			user = intent.getStringArrayExtra("user");

			if(intent.getIntArrayExtra("sum") == null){
				Log.e("sum","is null at StatisticDetailsActivity");
			}else{
				sum = intent.getIntArrayExtra("sum");
				location = intent.getStringArrayExtra("location");
				language = intent.getStringArrayExtra("language");
				followers = intent.getIntArrayExtra("followers");
				
				ExpandList = (ExpandableListView) findViewById(R.id.expandableList);
				
				ExpListItems = SetUserGroups();
				
				ExpAdapter = new StatisiticDetailsAdapter(StatisticDetailsActivity.this, ExpListItems);
		        ExpandList.setAdapter(ExpAdapter);
			}
		}
	}

	public ArrayList<ListGroup> SetPlaceGroups() {
    	ArrayList<ListGroup> list = new ArrayList<ListGroup>();
    	
    	for(int i=0; i<place.length; i++){
    		ArrayList<ListChild> childlist = new ArrayList<ListChild>();
    		ListChild sumChild = new ListChild("Count: "+sum[i]);
    		childlist.add(sumChild);
    		ListChild typeChild = new ListChild("Type: " + type[i]);
    		childlist.add(typeChild);
    		ListChild countryChild = new ListChild("Country: " + country[i]);
    		childlist.add(countryChild);
    		ListChild coordinatesChild = new ListChild("Coordinates: " + coordinates[i]);
    		childlist.add(coordinatesChild);
    		
    		ListGroup group = new ListGroup(place[i],childlist);
    		list.add(group);
    	}
        return list;
    }
	
	public ArrayList<ListGroup> SetUserGroups() {
    	ArrayList<ListGroup> list = new ArrayList<ListGroup>();
    	
    	for(int i=0; i<user.length; i++){
    		ArrayList<ListChild> childlist = new ArrayList<ListChild>();
    		ListChild sumChild = new ListChild("Count: "+sum[i]);
    		childlist.add(sumChild);
    		ListChild locationChild = new ListChild("Location: " + location[i]);
    		childlist.add(locationChild);
    		ListChild languageChild = new ListChild("Language: " + language[i]);
    		childlist.add(languageChild);
    		ListChild followersChild = new ListChild("Followers: " + followers[i]);
    		childlist.add(followersChild);
    		
    		ListGroup group = new ListGroup(user[i],childlist);
    		list.add(group);
    	}

        return list;
    }
	
	private void sort(int sortby){
		ListGroup temp = null;
    	for (int n=ExpListItems.size(); n>1; n=n-1){
    		for (int i=0; i<n-1; i=i+1){
    			if(sortby == 1){
    				if (ExpListItems.get(i).getName().compareTo(ExpListItems.get(i+1).getName()) > 0){
    					temp = ExpListItems.get(i);
	    				ExpListItems.set(i, ExpListItems.get(i+1));
	    				ExpListItems.set(i+1, temp);
	    			}
    			}else{
    				if(sortby == 2 || sortby == 5){
    					int first;
    					int second;
    					if(sortby == 2){
    						first = Integer.parseInt(ExpListItems.get(i).getItems().get(sortby-2).getName().substring(7));
    						second = Integer.parseInt(ExpListItems.get(i+1).getItems().get(sortby-2).getName().substring(7));
    					}else{
    						first = Integer.parseInt(ExpListItems.get(i).getItems().get(sortby-2).getName().substring(11));
    						second = Integer.parseInt(ExpListItems.get(i+1).getItems().get(sortby-2).getName().substring(11));
    					}
    					if (first < second){
    	    				temp = ExpListItems.get(i);
    	    				ExpListItems.set(i, ExpListItems.get(i+1));
    	    				ExpListItems.set(i+1, temp);
    	    			}
    				}else{
    					if (ExpListItems.get(i).getItems().get(sortby-2).getName().compareTo(ExpListItems.get(i+1).getItems().get(sortby-2).getName()) > 0){
    						temp = ExpListItems.get(i);
    						ExpListItems.set(i, ExpListItems.get(i+1));
    						ExpListItems.set(i+1, temp);
    					}
    				}
    			}
    		}
    	}
    }
	
	public class ListChild {

		private String Name;
		
		public ListChild(){
			
		}
		
		public ListChild(String Name){
			this.Name = Name;
		}
		
		public String getName() {
			return Name;
		}
		public void setName(String Name) {
			this.Name = Name;
		}
	}

	public class ListGroup {
		 
		private String Name;
		private ArrayList<ListChild> Items;
		
		public ListGroup(){
		}
		
		public ListGroup(String Name){
			this.Name = Name;
		}	
		
		public ListGroup(String Name, ArrayList<ListChild> Items){
			this.Name = Name;
			this.Items = Items;
		}
		
		public String getName() {
			return Name;
		}
		public void setName(String name) {
			this.Name = name;
		}
		public ArrayList<ListChild> getItems() {
			return Items;
		}
		public void setItems(ArrayList<ListChild> Items) {
			this.Items = Items;
		}
	}
	
	public class StatisiticDetailsAdapter extends BaseExpandableListAdapter {
		
		private Context context;
		private ArrayList<ListGroup> groups;
		
		public StatisiticDetailsAdapter(Context context, ArrayList<ListGroup> groups) {
			this.context = context;
			this.groups = groups;
		}
		
		public void addItem(ListChild item, ListGroup group) {
			if (!groups.contains(group)) {
				groups.add(group);
			}
			int index = groups.indexOf(group);
			ArrayList<ListChild> ch = groups.get(index).getItems();
			ch.add(item);
			groups.get(index).setItems(ch);
		}
		public Object getChild(int groupPosition, int childPosition) {
			ArrayList<ListChild> chList = groups.get(groupPosition).getItems();
			return chList.get(childPosition);
		}

		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view,
				ViewGroup parent) {
			ListChild child = (ListChild) getChild(groupPosition, childPosition);
			if (view == null) {
				LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = infalInflater.inflate(R.layout.statistic_details_child, null);
			}
			TextView tv = (TextView) view.findViewById(R.id.textChild);
			tv.setText(child.getName().toString());
			return view;
		}

		public int getChildrenCount(int groupPosition) {
			ArrayList<ListChild> chList = groups.get(groupPosition).getItems();

			return chList.size();

		}

		public Object getGroup(int groupPosition) {
			return groups.get(groupPosition);
		}

		public int getGroupCount() {
			return groups.size();
		}

		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		public View getGroupView(int groupPosition, boolean isLastChild, View view,
				ViewGroup parent) {
			ListGroup group = (ListGroup) getGroup(groupPosition);
			if (view == null) {
				LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = inf.inflate(R.layout.statistic_details_group, null);
			}
			TextView tv = (TextView) view.findViewById(R.id.textGroup);
			tv.setText(group.getName());
			return view;
		}

		public boolean hasStableIds() {
			return true;
		}

		public boolean isChildSelectable(int arg0, int arg1) {
			return true;
		}
	}
}
